import Interface
import Display
import Data

import requests
import io
import pygame
import json
import random
import tkinter as tk
from tkinter import StringVar
import threading

getUrl = "http://121.41.112.199:3000/song/url"
lyricUrl = "http://121.41.112.199:3000/lyric"


def playOrPause():
    global current_song_index
    if pygame.mixer.music.get_busy():
        pygame.mixer.music.pause()
        playStatus.set("继续")
    else:
        if current_song_index < len(playlist):
            pygame.mixer.music.load(playlist[current_song_index])
            pygame.mixer.music.play()
            current_song_index += 1
            if current_song_index >= len(playlist):
                current_song_index = 0
        playStatus.set("暂停")


def creatFrame():
    global nowPlayMusicName
    nowPlayMusicName = StringVar()
    global nowPlayMusicLyric
    nowPlayMusicLyric = StringVar()
    global playStatus
    playStatus = StringVar()
    # 播放列表
    global playlist
    playlist = []

    # 生成容器
    mainPlayFrame = tk.Frame(Interface.app, borderwidth=1, relief="raised")
    mainPlayFrame.pack(side='left', fill='both')
    tk.Label(mainPlayFrame, text="当前播放").pack(side='top', anchor="w", fill="both")
    tk.Label(mainPlayFrame, textvariable=nowPlayMusicName).pack(side='top', anchor="w", fill="both")
    # # 生成容器
    # controlPanelFrame = tk.Frame(mainPlayFrame, borderwidth=1, relief="raised")
    # controlPanelFrame.pack(side='top', fill='both')
    # tk.Button(controlPanelFrame, textvariable=playStatus, command=playOrPause).pack(side='top')
    # # tk.Button(controlPanelFrame, text="下一首", command=lambda current_song_index=current_song_index+1).pack(side='top')

    tk.Label(mainPlayFrame, text="播放列表：").pack(side='top', anchor="w", fill="both")
    # 播放列表（列表框）
    global playlist_listbox
    playlist_listbox = tk.Listbox(mainPlayFrame, width=50, height=10)
    playlist_listbox.pack()
    tk.Label(mainPlayFrame, text="歌词：").pack(side='top', anchor="w", fill="both")
    tk.Button(mainPlayFrame, text="选中此板块以使用滚轮", command=lambda type="play": Display.freshScro(type)).pack(side='top', anchor="w")

    # 创建画布和滚动条，Canvas,Scrollbar放置在主窗口上
    global playCanvas
    playCanvas = tk.Canvas(master=mainPlayFrame)
    playCanvas.pack(side='left', fill='both', expand=True)
    global playScro
    playScro = tk.Scrollbar(master=mainPlayFrame)
    playScro.pack(side='right', fill='y')

    # 生成容器
    lyricFrame = tk.Frame(playCanvas)
    lyricFrame.pack(side='top', anchor="w", fill="both")
    # 将Frame添加至Canvas上
    playCanvas.create_window(0, 3 * 30 + 100, window=lyricFrame, anchor="w")
    tk.Label(lyricFrame, textvariable=nowPlayMusicLyric).pack(side='top', anchor="w", fill="both")
    # 更新Frame大小，不然没有滚动效果
    lyricFrame.update()

    # 创建音乐播放线程
    creatPlayThread()


def requireLyricData(id):
    # 获取歌词数据
    getLyricUrl = lyricUrl + "?id=" + str(id)
    headers = {"Accept": "application/vnd.github.v3+json"}
    data = requests.get(getLyricUrl, headers=headers)
    lyricResponseDict = data.json()
    lyric = lyricResponseDict.get("lrc").get("lyric")
    return lyric


def requireMusicData(song):
    try:
        # 获取本地数据
        title = Data.checkLocalFile(song)
        if title == song.get("name"):
            musicFile = "C:/Users/TFC/Music/" + song.get("name") + "-"+song.get("artists")[0].get("name")+".mp3"
    except FileNotFoundError:
        # 获取网络音乐数据
        getMusicUrl = getUrl + "?id=" + str(song.get("id"))
        headers = {"Accept": "application/vnd.github.v3+json"}
        musicData = requests.get(getMusicUrl, headers=headers)
        musicResponseDict = musicData.json()
        musicFile = musicResponseDict["data"][0]["url"]
        try:
            # 保存网络音乐文件到内存
            content = requests.get(musicFile).content
            musicFile = io.BytesIO(content)
        except UnboundLocalError:
            musicFile = -1
    return musicFile


def play():
    global current_song_index
    current_song_index = 0
    # 初始化
    pygame.mixer.init()
    while True:
        if not pygame.mixer.music.get_busy():
            if current_song_index < len(playlist):
                musicFile = requireMusicData(playlist[current_song_index])
                lyricFile = requireLyricData(playlist[current_song_index].get("id"))
                # 更新显示
                nowPlayMusicName.set(f"{playlist[current_song_index].get("name")}-{playlist[current_song_index].get("artists")[0].get("name")}")
                nowPlayMusicLyric.set(lyricFile)
                # 播放
                pygame.mixer.music.load(musicFile)
                pygame.mixer.music.play()
                # 播放索引+1
                current_song_index += 1
            if current_song_index >= len(playlist):
                current_song_index = 0


def creatPlayThread():
    # 创建线程播放音乐,主线程用来接收用户操作
    t = threading.Thread(target=play)
    t.start()


def addPlayQueue(song):
    # 添加文件到播放列表
    playlist.append(song)
    # 更新播放列表显示
    playlist_listbox.delete(0, tk.END)
    for item in playlist:
        playlist_listbox.insert(tk.END, f"{item.get("name")}-{item.get("artists")[0].get("name")}")


def allPlay():
    global songs
    try:
        f = open('like_list.json', 'r', encoding="utf-8")
        content = f.read()
        # 将读取内容转化为字典
        songs = json.loads(content)
    except json.decoder.JSONDecodeError:
        songs = []

    # 打乱音乐顺序
    random.shuffle(songs)

    # 将歌曲添加到播放队列
    for song in songs:
        # 添加文件到播放列表
        playlist.append(song)
        # 更新播放列表显示
        playlist_listbox.delete(0, tk.END)
        for item in playlist:
            playlist_listbox.insert(tk.END, item)
